package com.huawei.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.huawei.basic.constant.VerifyConstants;
import com.huawei.basic.jwt.JwtUtils;
import com.huawei.basic.jwt.LoginData;
import com.huawei.basic.jwt.RsaUtils;
import com.huawei.basic.util.StrUtils;
import com.huawei.system.domain.Menu;
import com.huawei.user.domain.User;
import com.huawei.user.dto.BinderDto;
import com.huawei.basic.exception.BusinessException;
import com.huawei.basic.util.AjaxResult;
import com.huawei.basic.util.HttpUtil;
import com.huawei.basic.util.MD5Utils;
import com.huawei.user.constant.WxConstants;
import com.huawei.user.domain.Logininfo;
import com.huawei.basic.service.impl.BaseServiceImpl;
import com.huawei.user.domain.LoginDto;
import com.huawei.user.domain.Wxuser;
import com.huawei.user.mapper.LogininfoMapper;
import com.huawei.user.mapper.UserMapper;
import com.huawei.user.mapper.WxuserMapper;
import com.huawei.user.service.ILogininfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        String account = loginDto.getAccount();
        Integer loginType = loginDto.getLoginType();
        String password = loginDto.getPassword();

        //1.校验空值
        if (StringUtils.isEmpty(account)||StringUtils.isEmpty(loginType)||StringUtils.isEmpty(password)){
            throw new BusinessException("数据不能为空");
        }
        //3.校验账号
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if (logininfo==null){
            throw new BusinessException("账户或者密码错误");
        }
        //2.校验密码
        if (!logininfo.getPassword().equals(MD5Utils.encrypByMd5(password + logininfo.getSalt()))){
            throw new BusinessException("账户或者密码错误");
        }
        //1.3.状态校验 - 启用，禁用
        if(!logininfo.getDisable()){
            throw new BusinessException("你的账号被冻结，请联系管理员!!!");
        }
        /*//4.生成key【token】 将key和登录信息对象保存到redis
        String token = UUID.randomUUID().toString();
        //去掉密码和盐值 - 安全
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);*/

        Map<String, Object> map = loginSuccessJwtHander(logininfo);
        return map;
    }

    private Map<String, Object> loginSuccessJwtHander(Logininfo logininfo) {
        LoginData loginData = new LoginData();
        //将盐值密码设置为空
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        loginData.setLogininfo(logininfo);
        Map<String, Object> map = new HashMap<>();
        try {
            if (logininfo.getType()==0){
                //获取当前登录人的所有权限
                List<String> permissions = logininfoMapper.loadPermissionByLogininfoId(logininfo.getId());
                //获取当前登录人的所有菜单
                List<Menu> menus = logininfoMapper.loadMenusByLogininfoId(logininfo.getId());
                loginData.setPermissions(permissions);
                loginData.setMenus(menus);
                //将登录人的权限和菜单设置到map中，返回给前端
                map.put("permissions",permissions);
                map.put("menus",menus);
            }
            //通过私钥将登录信息加密
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            //将登录人的信息加密到jwtToken串
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 3000);
            //装到map返回
            map.put("token",jwtToken);
            map.put("logininfo",logininfo);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public AjaxResult wechatLogin(String code) {
        //1.根据code发送的请求获取token和openid
        System.out.println(code);
        String url = WxConstants.GET_ACK_URL
                .replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET)
                .replace("CODE",code);
        System.out.println(url);
        String jsonStr = HttpUtil.httpGet(url);

        //2.将响应的json字符串转换为json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        //3.通过openid去t_wxuser查询
        Wxuser wxuser = wxuserMapper.loadByOpenId(openid);

        if (wxuser!=null && wxuser.getUserId() != null){//绑定了
            Logininfo logininfo = logininfoMapper.loadLogininfoByUserId(wxuser.getUserId());

            Map<String, Object> map = loginSuccessJwtHander(logininfo);

            return AjaxResult.me().setResultObj(map);

        }else {
            //3.2 否则跳转到绑定页面
            Map<String, Object> map = new HashMap<>();
            map.put("access_token",access_token);
            map.put("openid",openid);
            return AjaxResult.me().setSuccess(false).setResultObj(map);

        }
    }

    @Override
    public AjaxResult binderLogin(BinderDto binderDto) {
        //校验空值
        String accessToken = binderDto.getAccessToken();
        String verifyCode = binderDto.getVerifyCode();
        String phone = binderDto.getPhone();
        String openId = binderDto.getOpenId();
        //2.校验 - 验证码是否过期  //code:1215215155
        Object redisCode = redisTemplate.opsForValue().get(VerifyConstants.BINDER_PREFIX + phone);
        if (redisCode==null){
            throw new BusinessException("验证码过期");
        }
        //3.校验 - 验证码是否正确
        if (!redisCode.toString().split(":")[0].equalsIgnoreCase(verifyCode.trim())){
            throw new BusinessException("验证码错误");
        }
        //绑定用户：t_wxUser【user_id】 绑定 t_user【id】
        //4.获取WxUser - 发送第三个请求 - json字符串
        String url = WxConstants.GET_USER_URL
                .replace("ACCESS_TOKEN",accessToken)
                .replace("OPENID",openId);
        String jsonStr = HttpUtil.httpGet(url);
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);

        //5.通过phone查询User
        User user = userMapper.loadByPhone(phone);
        //5.1.如果没有 - 根据phone创建User对象 - 创建Logininfo对象 - 保存Logininfo对象 - 保存User对象
        if (user==null){
            user = phone2User(phone);
            Logininfo logininfoTem = user2Logininfo(user);
            logininfoMapper.save(logininfoTem);
            user.setLogininfoId(logininfoTem.getId());
            userMapper.save(user);
        }
        //6.将User对象的id设置到WxUser对象中
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);

        //做免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());

        Map<String, Object> map = loginSuccessJwtHander(logininfo);

        return AjaxResult.me().setResultObj(map);
    }

    @Override
    public void logout(String token) {
        System.out.println(redisTemplate.opsForValue().get(token));
        redisTemplate.delete(token);

    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //随机的纯数字密码
        String randomPwd = StrUtils.getRandomString(6);
        String md5Pwd = MD5Utils.encrypByMd5(randomPwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("address"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }
}
